package main

import (
	"fmt"
	"os"

	"gitee.com/ebayboy/hyperscan"
)

func eventHandler(id uint, from, to uint64, flags uint, context interface{}) error {
	//inputData := context.([]byte)
	//	fmt.Printf("%s\n", inputData[from:to])

	return nil
}

var database hyperscan.BlockDatabase
var scratch *hyperscan.Scratch

func Match() {
	s1 := []byte("-axxxbyc-axxbyc-axbyc-")
	for i := 0; i < 3; i++ {
		if err := database.Scan(s1, scratch, eventHandler, s1); err != nil {
			fmt.Fprint(os.Stderr, "ERROR: Unable to scan input buffer. Exiting.\n")
			os.Exit(-1)
		}
	}

	s2 := []byte("-abzc-abzc-")
	for i := 0; i < 2; i++ {
		if err := database.Scan(s2, scratch, eventHandler, s2); err != nil {
			fmt.Fprint(os.Stderr, "ERROR: Unable to scan input buffer. Exiting.\n")
			os.Exit(-1)
		}
	}

	s3 := []byte("-aczc-")
	if err := database.Scan(s3, scratch, eventHandler, s3); err != nil {
		fmt.Fprint(os.Stderr, "ERROR: Unable to scan input buffer. Exiting.\n")
		os.Exit(-1)
	}
}

/*
#define RULES_HS_FLAGS   (HS_FLAG_CASELESS    | \
        HS_FLAG_SINGLEMATCH | \
        HS_FLAG_DOTALL)

#define RULES_HS_FLAGS_LEFTMOST        (HS_FLAG_CASELESS    | \
        HS_FLAG_DOTALL      | \
        HS_FLAG_SOM_LEFTMOST)
*/

func InitMod() {

	pattern := hyperscan.NewPattern("a(x*)b(y|z)c", hyperscan.DotAll|hyperscan.Caseless|hyperscan.SingleMatch)

	var err error
	database, err = hyperscan.NewBlockDatabase(pattern)
	if err != nil {
		fmt.Fprintf(os.Stderr, "ERROR: Unable to compile pattern \"%s\": %s\n", pattern.String(), err.Error())
		os.Exit(-1)
	}

	scratch, err = hyperscan.NewScratch(database)
	if err != nil {
		fmt.Fprint(os.Stderr, "ERROR: Unable to allocate scratch space. Exiting.\n")
		os.Exit(-1)
	}

	return
}

func main() {
	InitMod()
	Match()

	database.Close()
	scratch.Free()
}
